package com.ucode.cgms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ucode.cgms.mapper.CgmsCommissionFlowMapper;
import com.ucode.cgms.service.CgmsCommissionFlowService;
import com.ucode.model.cgms.CgmsCommissionFlow;
import com.ucode.model.cgms.enums.CgmsCommissionStatusEnum;
import com.ucode.tool.util.IdentifyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 佣金流水服务实现类
 * @Author: Claude
 * @Date: 2023/05/26 14:15
 * @Version: 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CgmsCommissionFlowServiceImpl implements CgmsCommissionFlowService {

    /**
     * 批量处理的大小
     */
    private static final int BATCH_SIZE = 500;

    @Resource
    private CgmsCommissionFlowMapper cgmsCommissionFlowMapper;

    @Override
    public CgmsCommissionFlowMapper initMapper() {
        return cgmsCommissionFlowMapper;
    }

    @Override
    public int updateStatus(Collection<Long> ids, Integer status) {
        return cgmsCommissionFlowMapper.updateStatus(ids, status);
    }

    @Override
    public Long createCommissionFlow(Long userId, Long orderId, BigDecimal orderAmount,
                                   BigDecimal amount, Integer commissionType, Integer commissionMode,
                                   BigDecimal returnPointAmount, BigDecimal commissionAmount) {
        CgmsCommissionFlow flow = new CgmsCommissionFlow();
        flow.setId(IdentifyUtils.getDefaultSnowflakeId());
        flow.setUserId(userId);
        flow.setOrderId(orderId);
        flow.setOrderAmount(orderAmount);
        flow.setAmount(amount);
        flow.setCommissionType(commissionType);
        flow.setReturnPointAmount(returnPointAmount);
        flow.setCommissionAmount(commissionAmount);
        // 设置初始状态为待结算(0)
        flow.setStatuz(CgmsCommissionStatusEnum.PENDING.getCode());
        
        this.insert(flow);
        return flow.getId();
    }
    
    @Override
    public int batchInsertCommissionFlow(List<CgmsCommissionFlow> list) {
        if (CollUtil.isEmpty(list)) {
            return 0;
        }
        
        // 为每条记录设置ID和状态
        for (CgmsCommissionFlow flow : list) {
            if (flow.getId() == null) {
                flow.setId(IdentifyUtils.getDefaultSnowflakeId());
            }
            if (flow.getStatuz() == null) {
                flow.setStatuz(CgmsCommissionStatusEnum.PENDING.getCode());
            }
        }
        
        // 分批处理，避免大事务
        int totalSize = list.size();
        int totalBatch = (totalSize + BATCH_SIZE - 1) / BATCH_SIZE; // 计算总批次
        int totalCount = 0;
        
        for (int i = 0; i < totalBatch; i++) {
            int fromIndex = i * BATCH_SIZE;
            int toIndex = Math.min((i + 1) * BATCH_SIZE, totalSize);
            List<CgmsCommissionFlow> subList = list.subList(fromIndex, toIndex);
            
            // 调用带有新事务的方法处理批次数据
            totalCount += getSelf().batchInsertWithNewTransaction(subList);
        }
        
        return totalCount;
    }
    
    /**
     * 在新事务中批量插入佣金流水
     * 使用REQUIRES_NEW确保每批次都在新事务中执行
     * 
     * @param batchList 待插入的佣金流水批次列表
     * @return 影响的行数
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public int batchInsertWithNewTransaction(List<CgmsCommissionFlow> batchList) {
        if (CollUtil.isEmpty(batchList)) {
            return 0;
        }
        return cgmsCommissionFlowMapper.batchInsert(batchList);
    }

    @Override
    public int batchSettle(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return 0;
        }
        // 将状态修改为已结算(1)
        return updateStatus(ids, CgmsCommissionStatusEnum.SETTLED.getCode());
    }
    
    @Override
    public int batchCancel(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return 0;
        }
        // 将状态修改为已取消(2)
        return updateStatus(ids, CgmsCommissionStatusEnum.CANCELLED.getCode());
    }
    
    @Override
    public List<CgmsCommissionFlow> getCommissionFlowByOrderId(Long orderId) {
        Map<String, Object> condition = new HashMap<>();
        condition.put("orderId", orderId);
        condition.put("deltag", false);
        
        return this.queryObjectForList(condition, 0);
    }

    /**
     * 获得自身的代理对象，解决 AOP 生效问题
     *
     * @return 自己
     */
    private CgmsCommissionFlowServiceImpl getSelf() {
        return SpringUtil.getBean(getClass());
    }
} 